package com.example.shgt;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TransactionRecordsActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private TransactionRecordAdapter adapter;
    private List<TransactionRecord> recordList;

    // 数据模型类
    public static class TransactionRecord {
        private String buyerAvatar;
        private long buyerId;
        private String buyerName;
        private long createTime;
        private String goodsDescription;
        private long goodsId;
        private long id;
        private List<String> imageUrlList;
        private int price;
        private String sellerAvatar;
        private long sellerId;
        private String sellerName;

        // Getters and Setters
        public String getBuyerAvatar() { return buyerAvatar; }
        public void setBuyerAvatar(String buyerAvatar) { this.buyerAvatar = buyerAvatar; }
        public long getBuyerId() { return buyerId; }
        public void setBuyerId(long buyerId) { this.buyerId = buyerId; }
        public String getBuyerName() { return buyerName; }
        public void setBuyerName(String buyerName) { this.buyerName = buyerName; }
        public long getCreateTime() { return createTime; }
        public void setCreateTime(long createTime) { this.createTime = createTime; }
        public String getGoodsDescription() { return goodsDescription; }
        public void setGoodsDescription(String goodsDescription) { this.goodsDescription = goodsDescription; }
        public long getGoodsId() { return goodsId; }
        public void setGoodsId(long goodsId) { this.goodsId = goodsId; }
        public long getId() { return id; }
        public void setId(long id) { this.id = id; }
        public List<String> getImageUrlList() { return imageUrlList; }
        public void setImageUrlList(List<String> imageUrlList) { this.imageUrlList = imageUrlList; }
        public int getPrice() { return price; }
        public void setPrice(int price) { this.price = price; }
        public String getSellerAvatar() { return sellerAvatar; }
        public void setSellerAvatar(String sellerAvatar) { this.sellerAvatar = sellerAvatar; }
        public long getSellerId() { return sellerId; }
        public void setSellerId(long sellerId) { this.sellerId = sellerId; }
        public String getSellerName() { return sellerName; }
        public void setSellerName(String sellerName) { this.sellerName = sellerName; }
    }

    // 响应模型类
    public static class TransactionRecordsResponse {
        private String msg;
        private int code;
        private Data data;

        public static class Data {
            private long current;
            private List<TransactionRecord> records;
            private long size;
            private long total;

            public long getCurrent() { return current; }
            public void setCurrent(long current) { this.current = current; }
            public List<TransactionRecord> getRecords() { return records; }
            public void setRecords(List<TransactionRecord> records) { this.records = records; }
            public long getSize() { return size; }
            public void setSize(long size) { this.size = size; }
            public long getTotal() { return total; }
            public void setTotal(long total) { this.total = total; }
        }

        public String getMsg() { return msg; }
        public void setMsg(String msg) { this.msg = msg; }
        public int getCode() { return code; }
        public void setCode(int code) { this.code = code; }
        public Data getData() { return data; }
        public void setData(Data data) { this.data = data; }
    }

    // 适配器类
    private class TransactionRecordAdapter extends RecyclerView.Adapter<TransactionRecordAdapter.ViewHolder> {
        private List<TransactionRecord> records;

        public TransactionRecordAdapter(List<TransactionRecord> records) {
            this.records = records;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public TextView buyerName, sellerName, goodsDescription, price, createTime;
            public ImageView buyerAvatar, sellerAvatar;

            public ViewHolder(View view) {
                super(view);
                buyerName = view.findViewById(R.id.tv_buyer_name);
                sellerName = view.findViewById(R.id.tv_seller_name);
                goodsDescription = view.findViewById(R.id.tv_goods_description);
                price = view.findViewById(R.id.tv_price);
                createTime = view.findViewById(R.id.tv_create_time);
                buyerAvatar = view.findViewById(R.id.iv_buyer_avatar);
                sellerAvatar = view.findViewById(R.id.iv_seller_avatar);
            }
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(R.layout.item_transaction_record, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            TransactionRecord record = records.get(position);
            holder.buyerName.setText(record.getBuyerName());
            holder.sellerName.setText(record.getSellerName());
            holder.goodsDescription.setText(record.getGoodsDescription());
            holder.price.setText("¥" + record.getPrice());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String formattedDate = sdf.format(new Date(record.getCreateTime()));
            holder.createTime.setText(formattedDate);

            // 检查 sellerAvatar
            if (record.getSellerAvatar() != null) {
                Glide.with(holder.itemView.getContext()).load(record.getSellerAvatar()).into(holder.sellerAvatar);
            } else {
                holder.sellerAvatar.setImageResource(R.drawable.touxiang); // 替换为您的占位图资源
            }

            // 检查 buyerAvatar
            if (record.getBuyerAvatar() != null) {
                Glide.with(holder.itemView.getContext()).load(record.getBuyerAvatar()).into(holder.buyerAvatar);
            } else {
                holder.buyerAvatar.setImageResource(R.drawable.touxiang); // 替换为您的占位图资源
            }
        }


        @Override
        public int getItemCount() {
            return records.size();
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transaction_records);

        recyclerView = findViewById(R.id.rv_transaction_records);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recordList = new ArrayList<>();
        adapter = new TransactionRecordAdapter(recordList);
        recyclerView.setAdapter(adapter);

        ImageView backButton = findViewById(R.id.iv_back);
        backButton.setOnClickListener(v -> finish());

        // 从 SharedPreferences 中获取用户 ID
        SharedPreferences sharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE);
        String userIdString = sharedPreferences.getString("userId", null);
        long userId = userIdString != null ? Long.parseLong(userIdString) : 0; // 确保有默认值

        fetchTransactionRecords(1, null, userId); // 请求第一页的交易记录
    }


    private void fetchTransactionRecords(int currentPage, String keyword, long userId) {
        String url = "https://api-store.openguet.cn/api/member/tran/trading/records?current=" + currentPage + "&size=10&userId=" + userId;

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .addHeader("appId", "479dbe79299a4653ada0432942111871")
                .addHeader("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("API Failure", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    Log.d("API Response", responseData);
                    parseResponseData(responseData);
                } else {
                    Log.e("API Error", "Response code: " + response.code());
                }
            }
        });
    }




    private void parseResponseData(String jsonData) {
        Gson gson = new Gson();
        TransactionRecordsResponse response = gson.fromJson(jsonData, TransactionRecordsResponse.class);

        if (response.getCode() == 200) {
            List<TransactionRecord> records = response.getData().getRecords();
            runOnUiThread(() -> {
                recordList.clear();
                recordList.addAll(records);
                adapter.notifyDataSetChanged();
                for (TransactionRecord record : records) {
                    Log.d("Avatar URLs", "Buyer: " + record.getBuyerAvatar() + ", Seller: " + record.getSellerAvatar());
                }
            });
        } else {
            // 处理错误信息
        }
    }

}
